clear;
clc;
close all;
addpath('../02_functions');
dbstop if error

%------------------------------------------------------------------------%
% This file creates figure 9(a,c) in the paper 
%------------------------------------------------------------------------%


% load ----------------------------------------------------------------------- 

file_name = '../01_data/es_quotes_5minute_EST';

% Call returns routine -----------------------------------------------------------------------

start_date              = datenum(2007,1,5);
finish_date             = datenum(2020,12,29);

winsorizing             = 1;
alpha                   = 0.99;
replace_option          = 1;

results                 = make_returns_288(file_name,start_date,finish_date,winsorizing,alpha,replace_option);
log_return_HbH_AD       = 100*252*results.log_return_HbH_AD;
log_return_AD           = 100*252*results.log_return_AD;
T                       = results.T;
caldt_daily             = results.caldt;


% ----------------------------------------------------------------% 
% LOAD TRADES
% ----------------------------------------------------------------% 

data = load('../01_Data/es_trades_5minute_EST.mat');
No_trades                                                                   = data.trades_per_min_mat;
No_contracts                                                                = data.trade_quantity_per_min_mat;
Signed_volume                                                               = data.signed_vol_per_min_mat;

beg_TRADES              = find_closest(data.caldt_daily,start_date);
fin_TRADES              = find_closest(data.caldt_daily,finish_date);

caldt_trades            = data.caldt_daily(beg_TRADES:fin_TRADES);
No_trades               = No_trades(beg_TRADES:fin_TRADES,:);
Volume                  = No_contracts(beg_TRADES:fin_TRADES,:);
Signed_volume           = Signed_volume(beg_TRADES:fin_TRADES,:);


% ----------------------------------------------------------------% 
% INTERSECT
% ----------------------------------------------------------------% 

[C,IA,IB]               = intersect(caldt_trades,caldt_daily);
caldt_daily             = caldt_daily(IB);
log_return_HbH_AD       = log_return_HbH_AD(IB,:);
log_return_AD           = log_return_AD(IB,:);

caldt_trades            = caldt_trades(IA);
No_trades               = No_trades(IA,:);
Volume                  = Volume(IA,:);
Signed_volume           = Signed_volume(IA,:);

% 15 min intervals
% 15 minute log returns
indx                    = [3 : 3 : length(Signed_volume(1,:))];
indx_loop               = [0 , indx];
Signed_volume_15b15_AD  = nan(size(Signed_volume,1),24*4);
Volume_15b15_AD         = nan(size(Volume,1),24*4);

for H = 1 : round(length(Signed_volume(1,:))/12*4)
    Signed_volume_15b15_AD(:,H)         = sum(Signed_volume(:,indx_loop(H)+1 : indx_loop(H+1)),2);
    Volume_15b15_AD(:,H)                = sum(Volume(:,indx_loop(H)+1 : indx_loop(H+1)),2);
end

lead = 1;

sum_signedVol_start         = 86;
sum_signedVol_end           = 89;

log_return_HbH_AD_lead                                  = log_return_HbH_AD(1+lead:end,:);
log_return_AD_lead                                      = log_return_AD(1+lead:end,:);
close_signed_volume_lead                                = sum(Signed_volume_15b15_AD(1:end-lead,sum_signedVol_start:sum_signedVol_end),2);
close_volume_lead                                       = sum(Volume_15b15_AD(1:end-lead,sum_signedVol_start:sum_signedVol_end),2);
indx_no_trading_EOD_volume_lead                         = find(close_volume_lead < 100);
close_volume_lead(indx_no_trading_EOD_volume_lead)      = nan;
close_rel_signed_volume_lead                            = close_signed_volume_lead./close_volume_lead;
Signed_volume_lead                                      = Signed_volume(1+lead:end,:);

caldt_true_lead                                         = caldt_daily(1+lead:end);
caldt_true                                              = caldt_daily;
close_signed_volume                                     = sum(Signed_volume_15b15_AD(:,sum_signedVol_start:sum_signedVol_end),2);
close_volume                                            = sum(Volume_15b15_AD(:,sum_signedVol_start:sum_signedVol_end),2);
indx_no_trading_EOD_volume                              = find(close_volume < 100);
close_volume(indx_no_trading_EOD_volume)                = nan;
close_rel_signed_volume                                 = close_signed_volume./close_volume;

% ----------------------------------------------------------------% 
% Sorts
% ----------------------------------------------------------------% 

portfolios = [-1000000000000000000 , -10000 , 0 , 10000, 10000000000000000000000000];
NN = length(portfolios)-1;

[caldt_close_rel_signedVol_sorted_lead , closing_rel_signedVol_sorted_lead]         = sort_High_Low_fixed(caldt_true_lead,close_signed_volume_lead,portfolios);
[caldt_close_rel_signedVol_sorted , closing_rel_signedVol_sorted]                   = sort_High_Low_fixed(caldt_true,close_signed_volume,portfolios);

% Check:
for p = 1 : NN
    min(closing_rel_signedVol_sorted_lead{p,1})
    max(closing_rel_signedVol_sorted_lead{p,1})
end

percentage = 100*length(find(closing_rel_signedVol_sorted_lead{2,1} >0))/length(closing_rel_signedVol_sorted_lead{2,1})

% ----------------------------------------------------------------% 
% find high ... low date intersections
% ----------------------------------------------------------------% 

for p = 1 : NN
    
    [C,IA,IB]                                   = intersect(caldt_close_rel_signedVol_sorted{p,1},caldt_true);
    caldt_close_rel_signedVol_sorted{p,1}       = caldt_close_rel_signedVol_sorted{p,1}(IA,:);
    closing_rel_signedVol_sorted{p,1}           = closing_rel_signedVol_sorted{p,1}(IA,:);
    caldt_daily_CTC_sorted{p,1}                 = caldt_true(IB);
    
    % contemporaneous
    log_return_HbH_AD_sorted{p,1}               = log_return_HbH_AD(IB,:);
    log_return_AD_sorted{p,1}                   = log_return_AD(IB,:); 
    
end


for p = 1 : NN

    [C,IA,IB]                                               = intersect(caldt_close_rel_signedVol_sorted_lead{p,1},caldt_true_lead);
    caldt_close_rel_signedVol_sorted_lead{p,1}              = caldt_close_rel_signedVol_sorted_lead{p,1}(IA,:);
    closing_rel_signedVol_sorted_lead{p,1}                  = closing_rel_signedVol_sorted_lead{p,1}(IA,:);
    caldt_daily_CTC_sorted_lead{p,1}                        = caldt_true_lead(IB);

    % next day
    log_return_HbH_AD_sorted{p,2}                           = log_return_HbH_AD_lead(IB,:);
    log_return_AD_sorted{p,2}                               = log_return_AD_lead(IB,:); 
    Signed_volume_sorted{p,1}                               = Signed_volume_lead(IB,:);
end


% ----------------------------------------------------------------% 
% cumulate for the drift
% ----------------------------------------------------------------%

for p = 1 : NN
    cum_logrets_sorted{p,1}                                 = [0 , nanmean(cumsum(log_return_AD_sorted{p,1},2))];
    cum_logrets_sorted{p,2}                                 = [0 , nanmean(cumsum(log_return_AD_sorted{p,2},2))];
    mu_cum_SV_sorted{p,1}                                   = [0 , nanmean(cumsum(Signed_volume_sorted{p,1},2))];
end

% ---------------------------------------------------------------------------------- %

% combine hourly plot and cumulative plot 


hour_index_1                = 1 : 289;
x_ticks_1                   = 1 : 12 : 289;
hour_string_1               = {'18', '19', '20' , '21' , '22' , '23' , '24' , '01' , '02' , '03', '04' , '05' , '06' , '07' , '08' , '09' , '10' , '11' , '12' , '13', '14' , '15' , '16', '17' , '18'};

sig_level                   = 1.69;
FS                          = 18;
LW                          = 5;

x_OD_start                  = 97; 
x_OD_end                    = 109; 
x_OR_start                  = 175; 
x_OR_end                    = 193; 
XX_OD                       = [x_OD_start x_OD_start x_OD_end   x_OD_end];
XX_OR                       = [x_OR_start x_OR_start x_OR_end   x_OR_end];

k = 2; % next day

y_min = 0;
y_max = 0;
for p = 1 : NN
   
    temp_min        = floor(min(cum_logrets_sorted{p,k})/1)*1
    y_min           = min(temp_min,y_min);

    temp_max        = ceil(max(cum_logrets_sorted{p,k})/1)*1
    y_max           = max(temp_max,y_max);
    
end


% ---------------------------------------------------------------------------------- %


mu_CTC          = 5.40;
detrend         = 0:(mu_CTC/288):mu_CTC;
y_min           = -15;
y_max           = 30;
YY              = [y_min y_max  y_max y_min  ];

figure
for p = 1 : NN
    hold on
    temp = cum_logrets_sorted{p,k};
    plot(hour_index_1,temp,'LineWidth',4);
end
hold on
plot(hour_index_1,zeros(1,length(hour_index_1)),'LineWidth',2,'color','black')
set(gca,'XTick',x_ticks_1,'XTickLabel',hour_string_1);
hold on
fill(XX_OD,YY  ,'k','FaceAlpha',0.1,'EdgeColor','none')
hold on
fill(XX_OR,YY  ,'k','FaceAlpha',0.1,'EdgeColor','none')
legend('SV<-10000','SV \in [-10000,0)', 'SV \in [0,10000]' , 'SV > 10000','Location','Northwest')
ylabel('Ann. avg. 5-min cum log return (in %, line)')
xlabel('Trade Time (ET)' )
xlim([1 146])

y_min       = -1200;
y_max       = 1700;

YY          = [y_min y_max  y_max y_min  ];

figure
for p = 1 : NN
    hold on
    temp = mu_cum_SV_sorted{p,1};
    plot(hour_index_1,temp,'LineWidth',4);
end
hold on
plot(hour_index_1,zeros(1,length(hour_index_1)),'LineWidth',2,'color','black')
set(gca,'XTick',x_ticks_1,'XTickLabel',hour_string_1);
fill(XX_OD,YY  ,'k','FaceAlpha',0.1,'EdgeColor','none')
hold on
fill(XX_OR,YY  ,'k','FaceAlpha',0.1,'EdgeColor','none')
legend('SV<-10000','SV \in [-10000,0)', 'SV \in [0,10000]' , 'SV > 10000','Location','Northwest')
ylabel('Cumulative Signed Volume')
xlabel('Trade Time (ET)' )
xlim([1 146])




